package com.compass.doctor.dialog

import android.graphics.drawable.ColorDrawable
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.Toast
import androidx.activity.viewModels

import androidx.appcompat.widget.ListPopupWindow
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.FragmentActivity
import com.compass.doctor.R
import com.compass.doctor.callback.OnCustomItemClick
import com.compass.doctor.callback.OnDrugSelectClick
import com.compass.doctor.databinding.DialogAppendDrugBinding
import com.compass.doctor.ui.home.viewmodel.DrugViewModel

import com.compass.doctor.ui.patient.adapter.PopupAdapter
import com.compass.framework.base.BaseDialog
import com.compass.framework.base.BaseDialogFragment
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.toBeanOrNull
import com.compass.framework.ext.toJson
import com.compass.framework.manager.AppManager
import com.compass.framework.manager.DictionariesManager
import com.compass.framework.model.Dictionaries
import com.compass.framework.model.Drug
import com.compass.framework.model.DrugItem
import com.compass.framework.toast.TipsToast
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.MoneyInputFilter
import com.compass.framework.utils.dpToPx
import com.netease.yunxin.kit.common.ui.utils.ToastUtils

/**
 * Description： 处方--添加药品 dialog
 * Date:2023/12/18 9:30
 */
class AppendDrugDialog {
    class Builder(
        activity: FragmentActivity,
        private var drugItem: DrugItem,
        private var intType: Int?,
        private var onDrugItemClick: OnDrugSelectClick?
    ) :
        BaseDialogFragment.Builder<Builder>(activity) {

        private val mBinding: DialogAppendDrugBinding =
            DialogAppendDrugBinding.inflate(LayoutInflater.from(activity))

        private lateinit var listPopupWindow: ListPopupWindow
        private lateinit var popupAdapter: PopupAdapter

        private var windowType = 0//弹出pop类型 1.给药频次 2.给药途径 3.用法
        private var num: Int = 1//默认药品数量
        private var days: String = "1"//默认药品天数
        private var drug: Drug = Drug()

        init {
            initView()
        }

        private fun initView() {
            setContentView(mBinding.root)
            setWidth((AppManager.getScreenWidthPx() * 0.85).toInt())
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT)
            setAnimStyle(BaseDialog.AnimStyle.DEFAULT)
            gravity = Gravity.CENTER_VERTICAL
            initData()
            initPopupWindow()
            intListener()
            initChineseView(drugItem.type)
            mBinding.tvDrugName.text = drugItem.name
            mBinding.tvSpecification.text =
                drugItem.spec?.let { String.format(it, drugItem.packingUnit) }
            mBinding.tvUnit.text = drugItem.minUnit
            mBinding.tvPackingUnit.text = drugItem.packingUnit
            val filter = MoneyInputFilter()
            filter.setMaxValue(999.99)
            filter.setDecimalLength(2)
            mBinding.tvUnitNum.filters = arrayOf(filter)
            mBinding.tvUnitNum.addTextChangedListener {
                it?.let {
                    drug.unitNum = it.toString()
                }
            }
            mBinding.tvExplain.addTextChangedListener {
                it?.let {
                    drug.explain = it.toString()
                }

            }


            val filterNumber = MoneyInputFilter()
            filterNumber.setMaxValue(999.99)
            filterNumber.setDecimalLength(2)
            mBinding.tvNum.filters = arrayOf(filterNumber)
            mBinding.tvNum.addTextChangedListener {

                var drugNumber=it.toString().trim()
                if (drugNumber.isEmpty()){
                    num=1
                    setDrugNumber()
                }else{
                    drug.num = it.toString()
                }




            }


            popupAdapter.setOnCustomItemClick(object : OnCustomItemClick {
                override fun onItemCallBack(position: Int, value: String, label: String) {
                    listPopupWindow.dismiss()
                    when (windowType) {
                        1 -> {
                            drug.frequency = value
                            drug.frequencyLabel = label
                            mBinding.tvFrequency.text = label
                        }

                        2 -> {
                            drug.channel = value
                            drug.channelLabel = label
                            mBinding.tvChannel.text = label
                        }

                        3 -> {
                            drug.usage = value
                            drug.usageLabel = label
                            mBinding.tvUsage.text = label
                        }
                    }
                }
            })
            //用药天数
            val filterDbp = MoneyInputFilter()
            filterDbp.setMaxValue(30.0)
            filterDbp.setDecimalLength(0)
            mBinding.tvNumberDay.filters = arrayOf(filterDbp)
        }

        private fun initData() {
            drug.specification = drugItem.spec
            drug.price = drugItem.price
            drug.drugId = drugItem.id
            drug.name = drugItem.name
            drug.packingUnit = drugItem.packingUnit
            drug.num = num.toString()
            drug.days = days
            drug.dosage = drugItem.minUnit
            drug.type = drugItem.type
            setDrugNumber()
        }

        private fun initChineseView(type: Int) {
            if (type != 1) {
                mBinding.llFrequency.gone()
                mBinding.llSingleDose.gone()
                mBinding.llAdministrationRoute.gone()
                mBinding.llUsage.gone()
                mBinding.llNumberDay.gone()
            }

        }

        private fun intListener() {

            mBinding.imgClose.onClick {
                dismiss()
            }
            mBinding.tvFrequency.onClick {
                initFrequency()
            }
            mBinding.tvChannel.onClick {
                initChannel()
            }
            mBinding.tvUsage.onClick {
                initUsage()
            }
            mBinding.tvMinusSign.onClick {
                num=drug.num.toInt()

                if (num > 1) num--
                setDrugNumber()
            }
            mBinding.tvPlusSign.onClick {
                num=drug.num.toInt()
                num++
                setDrugNumber()
            }

            mBinding.tvNumberDay.addTextChangedListener {
                days = it.toString().trim()
                drug.days = days
            }


            mBinding.tvSave.onClick {
                if (drugItem.type == 1) {
                    if (drug.frequency.isEmpty()) {
                        TipsToast.showTips("请选择给药频次")
                        return@onClick
                    }
                    if (drug.unitNum.isEmpty() || drug.unitNum == "0" || drug.unitNum == "0.0" || drug.unitNum == "0.00") {
                        TipsToast.showTips("请输入单次药量")
                        return@onClick
                    }
                    if (drug.channel.isEmpty()) {
                        TipsToast.showTips("请选择给药途径")
                        return@onClick
                    }
                    if (drug.usage.isEmpty()) {
                        TipsToast.showTips("请选择药品用法")
                        return@onClick
                    }
                    if (days.toInt() == 0) {
                        TipsToast.showTips("用药天数不能为0")
                        return@onClick
                    }
                }

                dismiss()
                onDrugItemClick?.onDrugSelectCallBack(drug)

            }
        }

        private fun setDrugNumber() {
            mBinding.tvNum.setText(num.toString())
            drug.num = num.toString()

        }


        private fun initPopupWindow() {
            listPopupWindow = ListPopupWindow(activity)
            val bgDrawable = ContextCompat.getDrawable(
                context,
                R.drawable.ps_permission_desc_bg
            )
            listPopupWindow.setBackgroundDrawable(bgDrawable)
            popupAdapter = PopupAdapter(activity)
            listPopupWindow.setAdapter(popupAdapter)
            listPopupWindow.width = LinearLayout.LayoutParams.WRAP_CONTENT
            listPopupWindow.isModal = true
        }


        private fun initFrequency() {
            windowType = 1
            listPopupWindow.height = dpToPx(200)
            listPopupWindow.anchorView = mBinding.tvFrequency

            popupAdapter.setList(
                DictionariesManager.getPrescriptionFrequency()
                    ?.toBeanOrNull<MutableList<Dictionaries>>()
            )
            LogUtil.e("给药途径==${DictionariesManager.getPrescriptionFrequency()}")
            listPopupWindow.show()

        }

        private fun initChannel() {
            windowType = 2
            listPopupWindow.height = LinearLayout.LayoutParams.WRAP_CONTENT
            listPopupWindow.anchorView = mBinding.tvChannel
            popupAdapter.setList(
                DictionariesManager.getPrescriptionChannel()
                    ?.toBeanOrNull<MutableList<Dictionaries>>()
            )
            LogUtil.e("给药途径==${DictionariesManager.getPrescriptionChannel()}")
            listPopupWindow.show()
        }


        private fun initUsage() {
            windowType = 3
            listPopupWindow.height = LinearLayout.LayoutParams.WRAP_CONTENT
            listPopupWindow.anchorView = mBinding.tvUsage
            popupAdapter.setList(
                DictionariesManager.getPrescriptionUsage()
                    ?.toBeanOrNull<MutableList<Dictionaries>>()
            )
            LogUtil.e("给药途径==${DictionariesManager.getPrescriptionUsage()}")
            listPopupWindow.show()
        }



    }
}